package com.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by leohe on 2017/7/29.
 */
@Component
public class MyStartupRunner implements CommandLineRunner,SerialPortEventListener {

    @Autowired
    private SerialPort serialPort;

    private InputStream inputStream;

    @Override
    public void run(String... strings) throws Exception {
        /*获取端口的输入流对象*/
        inputStream = serialPort.getInputStream();
        /*注册一个SerialPortEventListener事件来监听串口事件*/
        serialPort.addEventListener(this);
        /*设置监听器生效，即：当有数据时通知*/
        serialPort.notifyOnDataAvailable(true);
    }

    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {
        switch (serialPortEvent.getEventType()) {
            case SerialPortEvent.BI:/*Break interrupt,通讯中断*/
            case SerialPortEvent.OE:/*Overrun error，溢位错误*/
            case SerialPortEvent.FE:/*Framing error，传帧错误*/
            case SerialPortEvent.PE:/*Parity error，校验错误*/
            case SerialPortEvent.CD:/*Carrier detect，载波检测*/
            case SerialPortEvent.CTS:/*Clear to send，清除发送*/
            case SerialPortEvent.DSR:/*Data set ready，数据设备就绪*/
            case SerialPortEvent.RI:/*Ring indicator，响铃指示*/
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*Output buffer is empty，输出缓冲区清空*/
                System.out.println("输出缓冲区清空");
                break;

            case SerialPortEvent.DATA_AVAILABLE:/*Data available at the serial port，端口有可用数据。读到缓冲数组，输出到终端*/
                byte[] readBuffer = new byte[1];
                try {
                    List<Byte> l = new ArrayList<>();
                    while (inputStream.available() > 0) {
                        int numBytes = inputStream.read(readBuffer);
                        if (numBytes > 0) {
                            l.add(readBuffer[0]);
                        }
                    }
                    byte[] b = new byte[l.size()];
                    for (int i = 0 ; i < l.size() ; i++){
                        b[i] = l.get(i);
                    }
                    System.out.println(new String(b));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
